package com.item.service.item;

import com.item.pojo.Auth;
import com.item.pojo.Role;

import lombok.AllArgsConstructor;
import lombok.ToString;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.Objects;
@AllArgsConstructor
@Service
@ToString
public class UserDetailsServiceImpl implements UserDetailsService {
  private roleservicerimpl roleservice;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        PasswordEncoder passwordEncoderr=new BCryptPasswordEncoder();
        com.item.pojo.User user=roleservice.getuser(username);
        if(Objects.isNull(user))
        {
            System.out.println("user"+user);
            throw  new UsernameNotFoundException("用户不存在");
        }
        System.out.println("user"+user);
        LinkedList<GrantedAuthority> authorities=new LinkedList<>();
        for (Role role : roleservice.findrolebyusername(username)) {
            if(Objects.nonNull(role)){
                authorities.add(new SimpleGrantedAuthority(role.getRoleName()));

            }
        }
        for (Auth auth : roleservice.findauthbyusername(username)) {
            if(Objects.nonNull(auth)){
                authorities.add(new SimpleGrantedAuthority(auth.getUri()));

            }
        }
        System.out.println(authorities);
        return User.withUsername(username)
                .authorities(authorities)
                .password(passwordEncoderr.encode(user.getPassword()))
                .build()
                ;
    }

}
